import App from './App'
import store from './store'
// import manifest from './manifest.json'

import mqttTool from './lib/mqttTool.js'
Vue.prototype.$mqttTool = mqttTool

// uview依赖包
import uView from './uni_modules/uview-ui'
Vue.use(uView)

//储存是否订阅的变量
uni.setStorage({
	key: 'uuidlist',
	data: [],
	success: function() {
		console.log('uuidlist保存成功');
	}
});


uni.setStorage({
	key: 'subscribeInfo',
	data: []
});

uni.setStorage({
	key: 'publishInfo',
	data: []
});




// #ifndef VUE3
import Vue from 'vue'
Vue.config.productionTip = false
Vue.prototype.$store = store
Vue.prototype.$adpid = "1111111111"
Vue.prototype.$backgroundAudioData = {
	playing: false,
	playTime: 0,
	formatedPlayTime: '00:00:00'
}
App.mpType = 'app'
const app = new Vue({
	store,
	...App
})
app.$mount()
// #endif

// #ifdef VUE3
import {
	createSSRApp
} from 'vue'
import {
	methods
} from './uni_modules/uview-ui/libs/mixin/mixin'
export function createApp() {
	const app = createSSRApp(App)
	return {
		app
	}
}
// #endif

Vue.prototype.$baseUrl = "http://139.196.14.177:8080"
// Vue.prototype.$appVersionName = manifest.versionName


let opts = {
	// #ifdef APP
	url: 'wx://139.196.14.177:8085',
	// #endif

	clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
	username: 'root',
	password: 'root',
	clean: false,
	// clean: this.connectInfo.clean

}

var client = mqttTool.connect(opts);
client.on('connect', function(res) {
	console.log('mqtt connect success！');
	uni.showToast({title: "网络已连接"});
	// 取消订阅所有已订阅的主题
	var subscribedTopics = uni.getStorageSync('subscribedTopics') || [];
	subscribedTopics.forEach(topic => {
		client.unsubscribe(topic, (err) => {
			if (!err) {console.log(`Unsubscribed from ${topic}`);} 
			else {console.error(`Failed to unsubscribe from ${topic}:`, err);}
		});
	});
	// 重新订阅主题
	subscribedTopics.forEach(topic => {
		client.subscribe(topic, {qos: 0}, (err) => {if (!err) {console.log(`Subscribed to ${topic}`);}});
	});	
})
client.on('error', function(res) {
	console.log('mqtt connect failed！');
})
client.on('reconnect', () => {
	console.log('mqtt reconnecting...');
	uni.showToast({title: "网络重连中", icon: "loading"});
})
client.on('offline', ()=>{
	console.log('mqtt offline !');
	uni.showToast({title: "网络已断开", icon: "fail"});
})
client.on('end', () => {
	console.log('mqtt end');
})

export {
	client
}
